import { storeCommit, postReq, storeState, LStorage, LStorageClear, Router, getReq, obj_oto_query } from '@U/common'
import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import {
    accountStateHandle,
} from '@P/Login/Partner'
import { computed } from 'vue'
import { getPersonAccountDefAuth } from '@P/Auth/request'
import type { IObj } from '@/interface'
import { hasVarArray, hasVarObject } from '@/interface'

// 获取微信授权
export const getWeiXinPrivacyAuthorization = (hook = () => {}) => {
    /**
     * 微信于 2023-08-15/17 更新了隐私保护规则 (https://developers.weixin.qq.com/community/develop/doc/00042e3ef54940ce8520e38db61801)
     * uniapp在这个时间点并没有添加相应的接口，使用 @ts-ignore忽略未找到该方法的错误拦截
     */

    // #ifdef MP
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    wx.requirePrivacyAuthorize({
        success() {
            hook()
        },
        fail() {
            Msg({ icon: 'error', msg: '未授权' })
        },
    })
    // #endif
}

// 获取token
export const getToken = () => LStorage('shoudao_prm_token')
// 设置token
export const setToken = (token: string) => LStorage('shoudao_prm_token', token)
// 清除token
export const clearToken = () => {
    const sys = JSON.parse(JSON.stringify(storeState.system))
    const bottomSafeDis = JSON.parse(JSON.stringify(storeState.bottomSafeDis))
    storeCommit('init')
    storeCommit('system', sys)
    // 往vuex中再次存储bottomSafeDis
    storeCommit('bottomSafeDis', bottomSafeDis)
    LStorageClear()
}

// 获取refresh_token
export const getRefreshToken = () => LStorage('shoudao_prm_refresh_token')
// 设置refresh_token
export const setRefreshToken = (refresh_token: string) => LStorage('shoudao_prm_refresh_token', refresh_token)

// 获取mobile
export const getMobile = () => LStorage('shoudao_prm_mobile')
// 设置mobile
export const setMobile = (mobile: string) => LStorage('shoudao_prm_mobile', mobile)

// 获取加载完成状态
export const getLoginState = () => LStorage('shoudao_prm_login_state')
// 设置加载完成状态
export const setLoginState = (login_state: string) => LStorage('shoudao_prm_login_state', login_state)

// 当前账号类型 个人 | 企业
export const hasUserType = computed(() => storeState?.userType)

// 是否存在登陆后重定向
export const hasRedirect = (query: IObj) => {
    storeCommit('redirectPath', query.redirect)
    storeCommit('redirectParams', obj_oto_query(query?.redirectParams))
}

// 处理是否已登录
export const AccountInitialization = async () => {
    // 是否登录
    const isLogin = !!getToken()
    // 自动登录
    if (isLogin) {
        await MsgLoading('正在登录')
        const canLogin = await accountStateHandle()
        if (!canLogin) return
        return loginOK()
    }
}

// 注册
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
export const accountReg = async () => {
    // const type = ['', '个人', '企业'].indexOf(LStorage('shoudao_prm_reg_type'))
    // const RegWay = LStorage('shoudao_prm_invite_type') || 0
    const form = storeState.loginForm
    // 注册方式：0自主注册 1扫邀请码 2微信邀请 3朋友圈邀请 4短信邀请 5链接邀请
    const { code, data, msg } = await postReq('/api/channel-agent/account/reg', {
        mobile: form.username,
        verifyCode: form.password,
        regWay: storeState.meiDaoAI_invite_params?.regWay || 0,
        inviteCode: storeState.meiDaoAI_invite_params?.inviteCode || '',
    }).finally(() => {})
    if (code === 200) {
        MsgLoadingClear({ msg: '注册成功' })
        // LStorageClear('shoudao_prm_reg_type')
        // LStorageClear('shoudao_prm_invite_type')
        const { access_token, refresh_token, token_type } = data
        setToken(`${token_type} ${access_token}`)
        setRefreshToken(refresh_token)
        await MsgLoading()
        // const form = storeState.loginForm
        setMobile(storeState.loginForm.username)
        // -- 注册
        // if (LStorage('shoudao_prm_reg_type')) return accountReg()

        // 处理账户登录条件
        const canLogin = await accountStateHandle()
        if (!canLogin) return
        return loginOK()
    } Msg({ icon: 'error', msg: `注册失败 \n${msg}` })
}

// 新身份是否已存在
export const roleAlreadyExist = async (role: string) => {
    const { data } = await getReq('/api/identity/has-exist-identity', { inviteCode: role })
    if (data.hasExist) {
        // 审核或者通过
        if (data.status === 0 || data.status === 1) {
            Msg({ msg: '我们已经合作啦~不需要再扫啦~' })
        }
    }
    LStorage('hasExistData', JSON.stringify(data))
    return data
}

// 登录
export const accountLogin = async (url: string, form: IObj) => {
    const vertifyWay = ['pwd', 'vcode'].indexOf(form.type)
    const res = await postReq(url, {
        ...form,
        vertifyWay,
    }).finally(() => {})
    if (res.code === 200) {
        const { access_token, token_type, refresh_token = '' } = res.data
        const token = `${ token_type } ${ access_token }`
        // token
        setToken(token)
        setRefreshToken(refresh_token)
        return res
    } return res
}

// 重新获取token
export const refreshRequest = () => {
    const url = '/api/channel-agent/token/refresh'
    return postReq(url, { accessToken: getToken().slice(7), refreshToken: getRefreshToken() })
}
// 微信订阅
export const weixinSubscription = async () => {
    const { data: checkLoginWeiXin } = await postReq('/api/wx/miniprogram/channel-agent/check-mp-login')
    if (checkLoginWeiXin) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      uni.requestSubscribeMessage({
        tmplIds: ['lG_fQ3DCnXncjvZB35WaBWdVNs-LMagkI0eStrtjNDM', 'AKZ3ymr-s9A4Y1qNcX6BBozGw53MqY6LoGRH79XFyXU'],
        success: (subRes) => {
            console.log('subRes', subRes)
        },
        fail: (subErr) => {
          console.log('subErr', subErr)
        },
      })
    }
}
// 登录完成
export const loginOK = async (home?: string) => {
    await MsgLoading('正在登录')
    const { code, data } = await getPersonAccountDefAuth().finally(() => {})
    if (code === 200) {
        if (data.avatar === '') data.avatar = data.sex === 0 ? `${import.meta.env.VITE_SHOUDAO_OSS_URL}/boy.svg` : `${import.meta.env.VITE_SHOUDAO_OSS_URL}/girl.png`
        storeCommit('userAvatar', data.avatar)
        storeCommit('zhiKeInfo', data)
    }
    storeCommit('loginForm', {})
    // 首页 身份 邀请码 邀请码图片
    const _home = ''
    let _inviteCode = ''
    const { data: meidao_inviteCode } = await getReq('/api/channel-agent/invite-code/get').finally(() => {})
    _inviteCode = meidao_inviteCode
    const { data: meidao_inviteCodeImg } = await getReq('/api/wx/miniprogram/channel-agent/qrcode', { scene: `md_qrcode=${meidao_inviteCode}`, page: 'pages/Login/Login' }).finally(() => {})
    storeCommit('inviteCode', _inviteCode)
    storeCommit('inviteCodeImg', meidao_inviteCodeImg)
    storeCommit('requestSuccess', true)
    setLoginState('true')

    if (import.meta.env.DEV) {
        // 打印vuex localStorage
        let vuexText = '', localStorageText = ''
        Object.keys(storeState).forEach((key: string) => {
            if (key !== 'inviteCodeImg' && key !== 'system') {
                let value = storeState[key]
                value = (hasVarObject(value) || hasVarArray(value)) ? JSON.stringify(value) : value
                vuexText += `${key}: ${value}\n`
            }
        })
        Object.keys(LStorage()).forEach((key: string) => {
            localStorageText += `${key}: ${LStorage()[key]}\n`
        })
        console.log(`vuex:\n\n${vuexText}`)
        console.log(`localStorage:\n\n${localStorageText}`)
    }

    MsgLoadingClear()
    setTimeout(() => {
        const pageUrl = 'workbench'
        Router[storeState.redirectPath ? 'push' : 'reLaunch'](pageUrl || JSON.parse(JSON.stringify(storeState.redirectPath)) || _home, JSON.parse(JSON.stringify(storeState.redirectParams)))
        storeCommit('redirectPath', '')
        storeCommit('redirectParams', {})
    }, 100)

    // 获取微信登录授权
    const { data: checkLoginWeiXin } = await postReq('/api/wx/miniprogram/channel-agent/check-mp-login')
    if (!checkLoginWeiXin) {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        wx.login({
            success: async (res: IObj) => {
                const { code } = res
                await postReq('/api/wx/miniprogram/channel-agent/mp-login', { code })
            },
        })
    }
}
